﻿using MediatR;
using Microsoft.Data.SqlClient;
using S.Authorization.API.Application.Command.MenuListCountCommand;
using S.Authorization.Infrastructure;
using S.Authorization.Infrastructure.Impl.Menu;
using S.Authorization.Infrastructure.Interface.Menu;

namespace S.Authorization.API.Application.CommandHandlers.MenuListCountCommandHandler
{
    public class MenuCountCommandHandler : IRequestHandler<MenuCountCommand, int>
    {
        private readonly DbHelper dbHelper;
        private readonly IMenuRepository menuRepository;
        private readonly IMenuListCountRepository menuListCountRepository;
        public MenuCountCommandHandler(DbHelper _db, IMenuRepository _menuRepository, DbHelper _dbHelper, IMenuListCountRepository _menuListCountRepository) {  
            this.dbHelper = _db; 
            this.menuRepository = _menuRepository;
            this.menuListCountRepository = _menuListCountRepository;
        }
        public async Task<int> Handle(MenuCountCommand request, CancellationToken cancellationToken)
        {
            int menuId = request.MenuId;
            var menu = menuRepository.GetAllAsync().Result.FirstOrDefault(m => m.MenuId == menuId);
            var menucount = menuListCountRepository.GetAllAsync().Result.FirstOrDefault(m => m.MenuId == menuId);
            if (menucount == null)
            {
                string sqls = "INSERT INTO MenuListCount (MenuId,Path,Count) VALUES (@MenuId,@Path,1);";
                SqlParameter[] values =
                {
                    new SqlParameter("@MenuId",request.MenuId),
                    new SqlParameter("@Path",request.Path),
                };
                var list = await dbHelper.ExecuteNonQuery(sqls, values);
                return list; // 返回修改后的菜单项（可选）
            }
            else
            {
                if (menucount.MenuId == request.MenuId)
                {
                    menucount.Count = menucount.Count + 1;
                    string sql = "UPDATE MenuListCount SET Count=@Count WHERE MenuId=@MenuId";
                    SqlParameter[] value =
                    {
                    new SqlParameter("@Count",menucount.Count),
                    new SqlParameter("@MenuId",request.MenuId),
                };
                    var list = await dbHelper.ExecuteNonQuery(sql, value);
                    return list; // 返回修改后的菜单项（可选）
                }
                else
                {
                    string sqls = "INSERT INTO MenuListCount (MenuId,Path,Count) VALUES (@MenuId,@Path,1);";
                    SqlParameter[] values =
                    {
                    new SqlParameter("@MenuId",request.MenuId),
                    new SqlParameter("@Path",request.Path),
                };
                    var list = await dbHelper.ExecuteNonQuery(sqls, values);
                    return list; // 返回修改后的菜单项（可选）
                }
            }
        }
    }
}
